package com.epfresh.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.epfresh.R;
import com.epfresh.adapter.CategoryGoodsAdapter;
import com.epfresh.api.constant.AppPurchaseRouterConstant;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.utils.T;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.list.LoadMoreListViewFooter;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.Category;
import com.epfresh.bean.ProductCategory;
import com.epfresh.delegate.CategoryGoodsDelegate;
import com.epfresh.global.BaseActivity;
import com.epfresh.global.BaseFragment;
import com.epfresh.views.MultiStateView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Chen
 * Date: 2019/1/30
 * Desc:
 */
public class MarketGoodsFragment extends BaseFragment implements TabLayout.OnTabSelectedListener{
    public MultiStateView multiStateView;
    private TabLayout tabLayout;

    private List<Category> categoryList = new ArrayList<>();
    private String marketId;
    private List<String> marketIds;

    public CategoryGoodsDelegate cgDelegate;

    @Override
    public String getBaseTag() {
        return "marketGoodsFragment";
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        initIntent();
        return inflater.inflate(R.layout.fragment_goods_market, container, false);
    }

    private void initIntent() {
        Bundle bundle = this.getArguments();
        if (bundle != null) {
            marketId = bundle.getString("marketId");
            marketIds = new ArrayList<>();
            marketIds.add(marketId);
        }
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        reqCategory();
    }

    private void initView(View view) {
        multiStateView = view.findViewById(R.id.multi_state);
        multiStateView.setViewForState(R.layout.loading_view, MultiStateView.VIEW_STATE_LOADING);
        multiStateView.setViewForState(R.layout.empty_goods, MultiStateView.VIEW_STATE_EMPTY);
        multiStateView.setViewForState(R.layout.error_view, MultiStateView.VIEW_STATE_ERROR);
        multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
        tabLayout = view.findViewById(R.id.tl);
        tabLayout.addOnTabSelectedListener(this);

        FragmentActivity activity = getActivity();
        cgDelegate = new CategoryGoodsDelegate((BaseActivity) activity,this, view);
    }

    /**
     * 请求获取三级分类相关数据
     */
    private void reqCategory() {
        RequestEntityMap requestEntityMap = new RequestEntityMap();
        requestEntityMap.setCmd(AppPurchaseRouterConstant.cmd_store_category_tree4purchaser);
        String[] strings = new String[1];
        strings[0] = marketId;
        requestEntityMap.putParameter("marketIds", strings);
        request(requestEntityMap, AppPurchaseRouterConstant.cmd_store_category_tree4purchaser, new OnRequestListener<List<Category>>() {
            @Override
            public List<Category> jsonToObj(String responseStr) {
                return new Gson().fromJson(responseStr, new TypeToken<List<Category>>() {
                }.getType());
            }

            @Override
            public void onFail(int failCode, Object arg, Object tag) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onResponseError(int failCode, Object arg, Object tag) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_ERROR);
            }

            @Override
            public void onStart(Object tag) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_LOADING);
            }

            @Override
            public void onResponse(ResponseEntity<List<Category>> response, Object tag) {
                multiStateView.setViewState(MultiStateView.VIEW_STATE_CONTENT);
                List<Category> responseElement = response.getResponseElement();
                if (responseElement != null) {
                    categoryList.clear();
                    categoryList.addAll(responseElement);
                    initTl();
                    updateListStatus(0);
                }
            }
        });
    }

    /**
     * 初始化顶部tab栏
     */
    private void initTl() {
        for (int i = 0; i < categoryList.size(); i++) {
            tabLayout.addTab(tabLayout.newTab());
        }
        cusTabView();
    }

    private void cusTabView() {
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            if (tab != null) {
                tab.setCustomView(getTabView(i));
            }
        }
    }

    private View getTabView(int pos) {
        View tabView = LayoutInflater.from(getAppActivity()).inflate(R.layout.custom_tab_goods, null);
        ((TextView) tabView.findViewById(R.id.custom_tab)).setText(categoryList.get(pos).getName());
        return tabView;
    }

    private void updateListStatus(int i) {
        if (cgDelegate != null) {
            cgDelegate.dismissFilter();
        }
        if (i < categoryList.size()) {
            Category category = categoryList.get(i);
            List<ProductCategory> categories = category.getCategories();
            if (categories != null && categories.size() > 0) {
                for (int j = 0; j < categories.size(); j++) {
                    ProductCategory productCategory = categories.get(j);
                    productCategory.setSelect(false);
                }
                ProductCategory productCategory = categories.get(0);
                productCategory.setSelect(true);
            }
//            List<String > list = null;
//            if (mNameId != null){
//                list = new ArrayList<>();
//                list.add(mNameId);
//            }
            cgDelegate.updateList(category.getId(), categories,null,null, marketIds);
        }
    }


    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        cgDelegate.category2Pos = 0;
        updateListStatus(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }

}
